package com.chengweiyi.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chengweiyi.security.entity.Users;
import com.chengweiyi.security.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author xiao hu die
 * @Date 2022/5/8 22:40
 * @Version 1.0
 */
@Service(value = "userDetailsService")
public class MyUserByUserName implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
       /**根据用户名查询对象*/
        QueryWrapper<Users> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("name",s);
        Users users = usersMapper.selectOne(objectQueryWrapper);
        /**判断*/
        if (users==null){
           /**用户名不存在直接抛出异常*/
           throw new UsernameNotFoundException("该用户名不存在");
        }
        /**基于用户角色决定是否给予访问
         * 还可以基于用户权限决定是否有给予访问*/
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+users.getRole()+","+users.getPermissions());
        return new User(users.getUserName(),new BCryptPasswordEncoder().encode(users.getPassWord()),role);
    }
}
